import axios, {AxiosRequestConfig} from 'axios'
import {ElMessage} from 'element-plus'

const ip = '127.0.0.1'
// const ip = '192.168.56.10'

const httpInstance = axios.create({
    baseURL: `http://${ip}:10000`, timeout: 20000,
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    // const userStore = useUserStore()
    // 2. 按照后端的要求拼接token数据
    // const token = userStore.userInfo.token
    // if (token) {
    //     config.headers.Authorization = `Bearer ${token}`
    // }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(response => {  // 状态码  2xx
    // 这里的code是自定义的错误码
    if (response.data.code === 0) {
        return response
    } else {
        const errorMsg = response.data.msg
        ElMessage({type: 'error', message: errorMsg, duration: 10000})
        console.error(errorMsg)
        return Promise.resolve(null as any)
    }
}, error => { // 状态码 > 2xx, 400,401,403,404,500
    console.error(error) // 处理了异常
    if (error.response.status === 400) {
    } else if (error.response.status === 401) {
    }
    return Promise.resolve(null)
})

interface ResponseType<T> {
    code: number;
    msg: string;
    data: T;
}

// 统一加响应类型 ResponseType
export default async <T>(config: AxiosRequestConfig): Promise<T> => {
    const response = await httpInstance.request<ResponseType<T>>(config)
    let data = response?.data
    if (data) {
        const successMsg = data.msg;
        if (successMsg && successMsg != 'success') {
            ElMessage({type: 'success', message: successMsg})
        }
        return data.data;
    }
    return null as any;
}
